



Shadowing of static functions in Java


In Java, if name of a derived class static function is same as base class static function then the base class static function shadows (or conceals) the derived class static function. For example, the following Java code prints “A.fun()”
Note: Static method is a class property, so if static method is called from a class name or object having a class container then method of that class is called not the object’s method.







 


 

 













// file name: Main.java 
class A { 
   static void fun() { 
      System.out.println("A.fun()"); 
   } 
} 
  
class B extends A {  
   static void fun() {    
      System.out.println("B.fun()"); 
   } 
} 
  
public class Main { 
   public static void main(String args[]) { 
      A a = new B(); 
      a.fun();  // prints A.fun() 
   } 
} 


















If we make both A.fun() and B.fun() as non-static then the above program would print “B.fun()”.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.





Improved By :  NikhilJaiswal







 


 

 
Most popular in Java
 






 
More related articles in Java
 



 


 













